package com.nettywork.splitpacket;

import com.entity.User;
import com.util.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class SplitClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取服务端发送的数据
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object s) throws Exception {
        ByteBuf byteBuf = (ByteBuf)s;
        byte[] b = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(b);
        System.out.println(new String(b, CharsetUtil.UTF_8));
    }

    /**
     * 当客户端连接服务器完成的时候会调用该方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx){
        for(int i=0; i<10; i++){
            MyProtocol myProtocol = new MyProtocol();
            byte[] userB = new byte[2048];
            for(int n=0; n<2048; n++){
                userB[n] = 1;
            }
            User user = new User(i,"lvchao","13720169050");
            user.setB(userB);
            byte[] b = ProtostuffUtil.serialize(user);
            myProtocol.setLen(b.length);
            myProtocol.setContent(b);
            ctx.writeAndFlush(myProtocol);
        }
        System.out.println("发送数据成功");
    }

}
